package com.shiguiwu.springmybatis.netty.chat.group;

import com.shiguiwu.springmybatis.netty.chat.group.handler.GroupChatClientHandler;
import com.shiguiwu.springmybatis.netty.chat.group.handler.GroupChatServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * @description: 客户端
 * @author: stone
 * @date: Created by 2022/11/14 20:53
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.netty.chat.group
 */
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
@Data
public class GroupChatClient {

    private String address;

    private Integer port;

    public void run() {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sh) throws Exception {
                            //获取管理
                            ChannelPipeline pipeline = sh.pipeline();
                            //添加编解码器
                            pipeline.addLast("decoder", new StringDecoder())
                                    .addLast("encoder", new StringEncoder())
                                    .addLast(new GroupChatClientHandler());  //添加业务处理逻辑
                        }
                    });
            ChannelFuture future = bootstrap.connect(this.address, this.port).sync();
            //获取到通道
            Channel channel = future.channel();
            log.info("客户端输入=======================================>");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                //通过channel 发送到服务器端
                channel.writeAndFlush(msg + "\r\n");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new GroupChatClient("127.0.0.1", 8088).run();
    }


}
